/*
  Copyright 2012 Sergey Ostanin

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

package ru.irenproject;

import java.util.HashSet;
import java.util.Set;

import javax.inject.Inject;
import javax.inject.Singleton;

import org.apache.commons.lang3.Validate;

import ru.irenproject.store.AbstractThing;
import ru.irenproject.store.Kind;
import ru.irenproject.store.Thing;

import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.ImmutableMap;
import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.Descriptors.FieldDescriptor.Type;
import com.google.protobuf.Descriptors.FileDescriptor;

@Singleton public final class ProtoRegistry {
  private final ImmutableBiMap<Kind, Class<? extends AbstractThing>> fKindToThing;
  private final ImmutableMap<Descriptor, Kind> fShapeToKind;

  @Inject ProtoRegistry(Set<FileDescriptor> descriptors) {
    try {
      ImmutableBiMap.Builder<Kind, Class<? extends AbstractThing>> things = ImmutableBiMap.builder();

      ImmutableMap.Builder<Descriptor, Kind> shapes = ImmutableMap.builder();
      Set<Kind> shapeKinds = new HashSet<>();

      for (FileDescriptor fd : descriptors) {
        for (Descriptor d : fd.getMessageTypes()) {
          if (d.getOptions().hasExtension(BaseProtos.thing)) {
            Kind kind = Kind.get(d.getOptions().getExtension(BaseProtos.thing));
            Class<? extends AbstractThing> cls = Class.forName(d.getFullName())
                .asSubclass(AbstractThing.class);
            things.put(kind, cls);
          }

          if (d.getOptions().hasExtension(BaseProtos.shape)) {
            Kind kind = Kind.get(d.getOptions().getExtension(BaseProtos.shape));
            if (kind.value() != 0) {
              Validate.isTrue(shapeKinds.add(kind), "Duplicate shape kind %s.", kind);
            }
            shapes.put(d, kind);
          }
        }
      }

      fKindToThing = things.build();

      fShapeToKind = shapes.build();
      verifyShapes(fShapeToKind.keySet());
    } catch (ClassNotFoundException e) {
      throw new RuntimeException(e);
    }
  }

  private static void verifyShapes(Set<Descriptor> shapes) {
    for (Descriptor d : shapes) {
      if (!shapes.containsAll(getEmbeddedTypes(d))) {
        throw Oops.format("Shape %s contains a non-shape.", d.getFullName());
      }
    }
  }

  private static Set<Descriptor> getEmbeddedTypes(Descriptor d) {
    Set<Descriptor> res = new HashSet<>();
    for (FieldDescriptor fd : d.getFields()) {
      if (fd.getType() == Type.MESSAGE) {
        res.add(fd.getMessageType());
      }
    }
    return res;
  }

  public Kind getThingKind(Class<? extends Thing> thingClass) {
    return Validate.notNull(fKindToThing.inverse().get(thingClass),
        "No kind for %s.", thingClass);
  }

  public Class<? extends AbstractThing> getThingClass(Kind kind) {
    return Validate.notNull(getThingClassOrNull(kind), "Unknown kind %s.", kind);
  }

  public Class<? extends AbstractThing> getThingClassOrNull(Kind kind) {
    return fKindToThing.get(kind);
  }

  public Kind getShapeKind(Descriptor d) {
    Kind res = fShapeToKind.get(d);
    if (res == null) {
      throw Oops.format("%s is not a shape.", d.getFullName());
    }
    return res;
  }

  public void checkIsShape(Descriptor d) {
    if (!fShapeToKind.containsKey(d)) {
      throw Oops.format("%s is not a shape.", d.getFullName());
    }
  }
}
